package com.ingenio.siot;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.ResultSet;

import org.json.JSONObject;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class ObtenerRecorrido extends Adapter{
	
	public void guardarRecorrido(Integer id_movil, Integer id_recorrido, Integer id_ubicacion, Double lat, Double lng, String descripcion) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
	    	conn = (Connection) abrirConexion();
	    	String add ="INSERT into ubicaciones (IdMovil, IdRecorrido, IdUbicacion, latitud, longitud, descripcion) " +
					"VALUES (?, ?, ?, ?, ?, ?)";
			stmt = (PreparedStatement) conn.prepareStatement(add);
			stmt.setInt(1, id_movil);
			stmt.setInt(2, id_recorrido);
			stmt.setInt(3, id_ubicacion);
			stmt.setDouble(4, lat);
			stmt.setDouble(5, lng);
			stmt.setString(6, descripcion);
			stmt.execute();
		}
    	catch (Exception e) {
			e.printStackTrace();
			throw new Exception("Error al conectar con la base de datos.", e);
		}
    	finally{
    		//conn.close();
    		cerrarConexion(conn);
    	}
    }
	public Integer getIdRecorrido() throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
	    	conn = (Connection) abrirConexion();
	    	String sel ="Select MAX(IdRecorrido) as id from ubicaciones";
			stmt = (PreparedStatement) conn.prepareStatement(sel);
			ResultSet result = stmt.executeQuery();
			
			Integer id = null;
			if(result.next()){
			  id = result.getInt("id");	
			}
			return id;
		}
    	catch (Exception e) {
			e.printStackTrace();
			throw new Exception("Error al conectar con la base de datos.", e);
		}
    	finally{
    		//conn.close();
    		cerrarConexion(conn);
    	}
    }
	public void leerArchivo(String ruta){
		try{
			ObtenerRecorrido ob = new ObtenerRecorrido();
			FileInputStream fstream = new FileInputStream(ruta);
            DataInputStream entrada = new DataInputStream(fstream);
            BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));
            String strLinea;
            String[] parts;
            Integer id_ubicacion = 1;
            Integer id_movil = null;
            Integer id_recorrido = null;
            String descripcion = null;
            while ((strLinea = buffer.readLine()) != null)   {
                if(strLinea.contains(";") && !strLinea.contains("-")){
	                parts = strLinea.split(";");
	                String calle = new String(parts[0].replace(" ", "+").getBytes("UTF-8"), "ISO-8859-1");
	                JSONObject json = ObtenerCoordenadas.readJsonFromUrl("http://maps.googleapis.com/maps/api/geocode/json?address="+calle+"+"+parts[1]+"+rosario+argentina&sensor=false");
				    JSONObject location = json.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location"); 
				    Double lat = location.getDouble("lat");
				    System.out.println(lat);
				    Double lng = location.getDouble("lng");
				    ob.guardarRecorrido(id_movil, id_recorrido, id_ubicacion, lat, lng, descripcion);
				    id_ubicacion++;
				}else if(strLinea.contains("-")){
					id_ubicacion = 1;
					parts = strLinea.split("-");
					System.out.println(parts[1]);
					id_movil = Integer.parseInt(parts[0]);
					id_recorrido = ob.getIdRecorrido()+1;
					descripcion = parts[1];
				}
            }
            entrada.close();
        }catch (Exception e){ //Catch de excepciones
            System.err.println("Ocurrio un error: " + e.getMessage());
        }
	}	
	public static void main(String[] args){
		ObtenerRecorrido or = new ObtenerRecorrido();
		or.leerArchivo("C:\\recorrido254.txt");
		System.out.println("Done!");
	}
}
